import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_wan_android/bean/article_list_bean.dart';
import 'package:flutter_wan_android/bean/banner_bean.dart';
import 'package:flutter_wan_android/bean/home_data.dart';
import 'package:flutter_wan_android/bean/project_list_bean.dart';
import 'package:flutter_wan_android/blocs/base/bloc_provider.dart';
import 'package:flutter_wan_android/blocs/home_bloc.dart';
import 'package:flutter_wan_android/res/colors.dart';
import 'package:flutter_wan_android/res/dimens.dart';
import 'package:flutter_wan_android/res/strings.dart';
import 'package:flutter_wan_android/ui/webview/webview_page.dart';
import 'package:flutter_wan_android/utils/navigator_utils.dart';
import 'package:flutter_wan_android/widgets/app_bar_widget.dart';
import 'package:flutter_wan_android/widgets/empty_widget.dart';
import 'package:flutter_wan_android/widgets/home_widgets.dart';
import 'package:flutter_wan_android/widgets/home_widgets.dart' as prefix0;
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  HomeBloc _homeBloc;
  EasyRefreshController _refreshControllerE;
  RefreshController _refreshController = RefreshController();
  ScrollController _scrollController=ScrollController();

  @override
  void initState() {
    super.initState();
    _refreshControllerE = EasyRefreshController();
    _homeBloc = BlocProvider.of<HomeBloc>(context);
    _refresh();

    _scrollController.addListener((){
//      print("offset:::${_scrollController.offset}");

    });

  }

  void _refresh() {
    Future.delayed(Duration(seconds: 2),(){
      _homeBloc.getHomeData(1);
    });

  }

  @override
  Widget build(BuildContext context) {
    return buildScaffold();
  }

  Scaffold buildScaffold() {
    return Scaffold(
      appBar: PreferredSize(
          child: AppBar(
            centerTitle: true,
              title: Text(
            Strings.homeTitle,

            style: TextStyle(
              fontSize: XDimens.appBarTitleTextSize,
              color: Colors.white,
            ),
          )),
          preferredSize: Size.fromHeight(XDimens.appBarHeight)),
      body: buildStreamBuilder());
  }

  StreamBuilder<HomeData> buildStreamBuilder() {
    return StreamBuilder(
        stream: _homeBloc.homeStream,
        builder: (context, AsyncSnapshot<HomeData> snapshot) {
          _refreshController.refreshCompleted();


          if (snapshot.hasError) {
            return ErrorView(error: snapshot.error.toString(),onTap: (){
              _refresh();
            },);
          }

          if (!snapshot.hasData) {
            return LoadingView();
          }



          return SmartRefresher(
            header: TwoLevelHeader(
              textStyle: TextStyle(color: Colors.white),
              displayAlignment: TwoLevelDisplayAlignment.fromTop,
              decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage("images/second_floor.jpg"),
                    fit: BoxFit.cover,
                    // 很重要的属性,这会影响你打开二楼和关闭二楼的动画效果
                    alignment: Alignment.topCenter),
              ),
              twoLevelWidget: TwoLevelWidget(),
            ),
            child: buildListView(context, snapshot),
            controller: _refreshController,
            enableTwoLevel: true,
            enablePullDown: true,
            enablePullUp: false,
            onLoading: () async {

            },
            onRefresh: () async {
              _refresh();
            },
            onTwoLevel: () {},
          );;
        });
  }

  @Deprecated("不使用")
  EasyRefresh buildEasyRefresh(AsyncSnapshot<HomeData> snapshot) {
    return EasyRefresh.custom(
            controller: _refreshControllerE,
            onRefresh: () async {
              _refresh();
              _refreshControllerE.resetRefreshState();
              _refreshControllerE.resetLoadState();
            },
            onLoad: () async {
              _refreshControllerE.finishLoad(success: true, noMore: true);
            },
            slivers: <Widget>[
              SliverList(
                  delegate: SliverChildBuilderDelegate((context, index) {
                if (index == 0) {
                  return buildBanner(context, snapshot.data.bannerLists);
                } else if (index == 1) {
                  return buildProjectList(snapshot.data.projectLists);
                } else if (index == 2) {
                  return buildArticleList(snapshot.data.articleLists);
                }
                return Container(
                  height: 0,
                );
              }, childCount: 3))
            ]);
  }

  ListView buildListView(
      BuildContext context, AsyncSnapshot<HomeData> snapshot) {
    return ListView(
      controller: _scrollController,
      children: <Widget>[
//        CommonAppBar("首页").build(context),
        buildBanner(context, snapshot.data.bannerLists),
        buildProjectList(snapshot.data.projectLists),
        buildArticleList(snapshot.data.articleLists),

      ],
    );
  }

  ///AspectRatio:子树按比率来填充整个布局区域
  ///https://www.jianshu.com/p/c997b381e4a4
  Widget buildBanner(BuildContext context, List<BannerBean> list) {
    if (list == null || list.isEmpty) {
      return Container(
        height: 0,
      );
    }
    return AspectRatio(
        aspectRatio: 2.0,
        child: Container(
          margin: EdgeInsets.only(top: 8.0),
          child:  Swiper(
            itemCount: list.length,
            itemBuilder: (context, int index) {
              BannerBean bannerBean = list[index];
              return ClipRRect(
                  borderRadius: BorderRadius.circular(8.0),
                  child: CachedNetworkImage(
                    fit: BoxFit.fill,
                    imageUrl: bannerBean.imagePath,
                    placeholder: (context, url) => ProgressView(),
                    errorWidget: (context, url, object) => Icon(Icons.error),
                  ));
            },
            pagination: new SwiperPagination(
              builder: const DotSwiperPaginationBuilder(
                  size: 6.0, activeSize: 6.0, space: 3.0),
            ),
            control: null,
            autoplay: true,
            viewportFraction: 0.85,
            scale: 0.9,
            onTap: (index){
              BannerBean bannerBean = list[index];
              NavigatorUtils.push(context, WebViewPage(bannerBean.url,bannerBean.title));
            },
          ),
        ));
  }

  Widget buildProjectList(List<ProjectItem> data) {
    if (data == null || data.isEmpty) {
      return Container(
        height: 0,
      );
    }

    if (data.length >= 6) {
      data = data.sublist(0, 6);
    }
    List<Widget> children = List();

    children.add(HeaderItemView(prefix0.Header.project,
        leftIcon: Icons.import_contacts, leftTitle: '最新项目', leftColor: 0));
    data.forEach((item) => children.add(ProjectItemView(item)));

    return Container(
        alignment: Alignment.center,
        child: Column(
          children: children,
        ));
  }

  Widget buildArticleList(List<ArticleItem> data) {
    if (data == null || data.isEmpty) {
      return Container(
        height: 0,
      );
    }

    if (data.length >= 6) {
      data = data.sublist(0, 6);
    }
    List<Widget> children = List();
    children.add(HeaderItemView(prefix0.Header.article,
        leftIcon: Icons.chrome_reader_mode, leftTitle: '推荐文章', leftColor: 0));
    data.forEach((item) => children.add(ArticleItemView(
          item
        )));

    return Container(
        alignment: Alignment.center,
        child: Column(
          children: children,
        ));
  }
}



class TwoLevelWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
            image: AssetImage("images/second_floor.jpg"),
            // 很重要的属性,这会影响你打开二楼和关闭二楼的动画效果,关联到TwoLevelHeader,如果背景一致的情况,请设置相同
            alignment: Alignment.topCenter,
            fit: BoxFit.cover),
      ),
      child: Stack(
        children: <Widget>[
          Center(
            child: Wrap(
              children: <Widget>[

              ],
            ),
          ),
          Container(
            height: 40.0,
            margin: EdgeInsets.only(left: 10),
            child: GestureDetector(
              child: Icon(
                Icons.arrow_back,
                color: Colors.white,
              ),
              onTap: () {
                SmartRefresher.of(context).controller.twoLevelComplete();
              },
            ),
            alignment: Alignment.bottomLeft,
          )
        ],
      ),
    );
  }
}
